import 'dart:math';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/my/user_page_logic.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/mode_config.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/view/expert/items/expert_logo.dart';
import 'package:sports_new/view/expert/items/suggest_expert_widget.dart';
import 'package:sports_new/view/expert/plan_pack/plan_pack_card.dart';
import 'package:sports_new/view/my/user_page/user_plan_form_list.dart';
import 'package:sports_new/view/my/user_page/user_publish_list.dart';
import 'package:sports_new/view/my/user_page/user_viewpoint_list.dart';
import 'package:sports_new/view/pick/items/expert_record_tag.dart';
import 'package:sports_new/widgets/base/qkd_button.dart';
import 'package:sports_new/widgets/focus_button.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/share/share_button.dart';
import 'package:visibility_detector/visibility_detector.dart';
import '../../../utils/routes.dart';
import '../../../utils/user.dart';
import '../../../widgets/base/qkd_text.dart';
import '../../../widgets/share/share_image.dart';
import '../../pick/subs/subs_bar.dart';

class UserPage extends StatefulWidget {
  const UserPage({super.key});

  @override
  State<UserPage> createState() => _UserPageState();
}

class _UserPageState extends State<UserPage> with TickerProviderStateMixin {
  late final UserPageLogic logic;
  double random = Random().nextDouble() * 10000;

  @override
  void initState() {
    logic = Get.put(UserPageLogic(), tag: '${Get.arguments}$random');
    Utils.onEvent("zj_ck");
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<UserPageLogic>(
        tag: '${Get.arguments}$random',
        builder: (logic) {
          return VisibilityDetector(
            key: const Key('user_page'),
            onVisibilityChanged: (info) {
              if (!info.visibleBounds.isEmpty && logic.data != null) {
                logic.getData(isNew: false);
              }
            },
            child: Scaffold(
              extendBodyBehindAppBar: true,
              appBar: Styles.appBar(
                titleSpacing: 0,
                toolbarHeight: 44,
                leadingColor: Colours.white,
                title: logic.showTop
                    ? Styles.userAppbarTitle(
                        logo: logic.data?.userLogo,
                        name: logic.data?.userName,
                        focus: logic.data?.isFocus,
                        userId: logic.data?.userId,
                        expertId: logic.data?.expertId,
                        color: Colours.white,
                        onTap: (value) {
                          logic.getData(isNew: false);
                        })
                    : null,
                backgroundColor:
                    logic.showTop ? Colours.main : Colours.transparent,
                systemUiOverlayStyle: const SystemUiOverlayStyle(
                  statusBarIconBrightness: Brightness.light,
                ),
                actions: [
                  ShareButton(
                    route: 'tg/homePage/${logic.id}/?sportsId=${logic.type}',
                    title: "听说这个专家挺厉害的",
                    logoUrl: logic.data?.userLogo,
                    needChannel: true,
                    imageWidget: <Widget>() {
                      if (logic.listType[logic.tabIndex] == ListType.soccer ||
                          logic.listType[logic.tabIndex] == ListType.basket) {
                        return ShareImage.expert(
                            param:
                                'tg/homePage/${logic.id}/?sportsId=${logic.type}',
                            widgets: [
                              header(isShare: true),
                              if (logic.listType[logic.tabIndex] ==
                                  ListType.soccer) ...[
                                UserViewPointList(1, logic.data!.expertId!,
                                    isShare: true)
                              ] else if (logic.listType[logic.tabIndex] ==
                                  ListType.basket) ...[
                                UserViewPointList(2, logic.data!.expertId!,
                                    isShare: true)
                              ]
                            ]);
                      }
                    },
                    onTap: () => Utils.onEvent("expert_detail_share",
                        params: {"expert_id": logic.data?.expertId}),
                  ).paddingOnly(right: 16),
                ],
              ),
              body: Stack(
                alignment: Alignment.topCenter,
                children: [
                  Image.asset(Utils.getImgPath('user_header_bg.png')),
                  ExtendedNestedScrollView(
                    controller: logic.scrollC,
                    pinnedHeaderSliverHeightBuilder: () =>
                        MediaQuery.of(context).padding.top + 44,
                    headerSliverBuilder:
                        (BuildContext context, bool innerBoxIsScrolled) {
                      return <Widget>[
                        SliverToBoxAdapter(
                            child: header()
                                .paddingOnly(top: Get.width * 111 / 375))
                      ];
                    },
                    body: LoadingWidget<bool>(
                        isLoading: logic.data == null,
                        data: logic.tabs.isEmpty,
                        child: body),
                  ),
                ],
              ),
            ),
          );
        });
  }

  Widget header({bool isShare = false}) {
    return Container(
      decoration: const BoxDecoration(
          color: Colours.white,
          border: Border(bottom: BorderSide(color: Colours.greyEE, width: 0.5)),
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(8), topRight: Radius.circular(8))),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            SizedOverflowBox(
              alignment: Alignment.bottomCenter,
              size: const Size(114, 60),
              child: ExpertLogo(
                logo: logic.data?.userLogo ?? '',
                hasAuth: logic.data?.isInvite == 1,
                size: 80,
                authSize: 20,
              ),
            ),
            const Spacer(),
            headerData('${logic.data?.fansCnt ?? '-'}', '粉丝'),
            if (!isShare) ...[
              Container(
                  width: 0.5,
                  height: 16,
                  color: Colours.greyEE,
                  margin: const EdgeInsets.only(bottom: 14)),
              headerData('${logic.data?.subsCnt ?? '-'}', '订阅'),
              Container(
                  width: 0.5,
                  height: 16,
                  color: Colours.greyEE,
                  margin: const EdgeInsets.only(bottom: 14)),
              headerData('${logic.data?.planCnt ?? '-'}', '方案')
            ]
          ],
        ),
        const SizedBox(height: 9),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          child: Row(
            children: [
              QkdText(
                logic.data?.userName ?? '',
                fontSize: 20,
                fontWeight: FontWeight.w500,
              ),
              const Spacer(),
              if (logic.id != User.info?.id && !isShare)
                FocusButton(logic.data?.isFocus ?? 0,
                    width: 80,
                    height: 30,
                    userId: logic.data?.userId,
                    expertId: logic.data?.expertId, onTap: (value) {
                  if (value == 1) logic.showFocusMore = true;
                  logic.getData(isNew: false);
                  Utils.onEvent("expert_detail_follow", params: {
                    "expert_id": logic.data?.expertId,
                    "follow": value
                  });
                }),
              if (logic.id == User.info?.id && !isShare)
                QkdButton(
                    width: 80,
                    height: 30,
                    borderRadius: 4,
                    foregroundColor: Colours.grey99,
                    text: "编辑资料",
                    textStyle: const TextStyle(fontSize: 14),
                    borderSide:
                        const BorderSide(width: 0.5, color: Colours.greyCC),
                    onPressed: () {
                      Utils.onEvent("my_page_edit");
                      Get.toNamed(Routes.myEditInfo)
                          ?.then((value) => logic.getData());
                    })
            ],
          ),
        ),
        if (logic.data?.tagItems.hasValue == true)
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Image.asset(width: 16, Utils.getImgPath("user_tag_icon.png")),
              Container(width: 4),
              const QkdText("荣誉认证：",
                      needCenter: true, fontSize: 12, color: Colours.grey66)
                  .paddingOnly(top: 2),
              Expanded(
                child: Wrap(
                        spacing: 8,
                        runSpacing: 11,
                        children: logic.data?.tagItems
                                ?.map((e) => e.style == 5
                                    ? Image.asset(
                                        Utils.getImgPath(
                                            "expert_invite_tag.png"),
                                        width: 48,
                                        height: 14)
                                    : ExpertRecordTag(
                                        type: e.style, text: e.name))
                                .toList() ??
                            [])
                    .paddingOnly(top: 1),
              )
            ],
          ).paddingOnly(top: 11, left: 16),
        if (logic.data?.leagueTop?.hasValue == true && ModeConfig.expertRecord)
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () =>
                Get.toNamed(Routes.expertLeagues, arguments: logic.data),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const QkdText("擅长联赛：",
                        needCenter: true, fontSize: 12, color: Colours.grey66)
                    .paddingOnly(top: 2),
                Flexible(
                  child: Wrap(
                          spacing: 8,
                          runSpacing: 11,
                          children: logic.leagues
                                  ?.map((e) => GestureDetector(
                                        onTap: () => Get.toNamed(
                                            Routes.expertLeagueList,
                                            arguments: e),
                                        child: Row(
                                          mainAxisSize: MainAxisSize.min,
                                          children: [
                                            Container(
                                              clipBehavior: Clip.antiAlias,
                                              height: 17,
                                              alignment: Alignment.center,
                                              padding:
                                                  const EdgeInsets.symmetric(
                                                      horizontal: 6),
                                              decoration: BoxDecoration(
                                                gradient: const LinearGradient(
                                                    colors: [
                                                      Color(0xFFFEAF24),
                                                      Color(0xFFFFBF4F)
                                                    ]),
                                                borderRadius:
                                                    BorderRadius.circular(4),
                                              ),
                                              child: QkdText(e.leagueName ?? "",
                                                  height: 1.172,
                                                  fontSize: 12,
                                                  color: Colours.white),
                                            ),
                                          ],
                                        ),
                                      ))
                                  .toList() ??
                              [])
                      .paddingOnly(top: 1),
                ),
                Container(width: 8),
                Image.asset(Utils.getImgPath('arrow_right_36.png'), width: 12)
              ],
            ).paddingOnly(top: 11, left: 16),
          ),
        const SizedBox(height: 11),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          child: QkdText(
            logic.data?.introduction.hasValue == true
                ? logic.data!.introduction!
                : '暂无介绍',
            maxLines: 2,
            color: Colours.grey66,
            fontSize: 12,
          ),
        ),
        PlanPackCard(
          expertId: logic.id,
          margin: const EdgeInsets.fromLTRB(16, 8, 16, 0),
        ),
        if (logic.showFocusMore && logic.sportsId != 0)
          SuggestExpertWidget.list(sportsId: logic.sportsId)
        else
          Container(height: 20),
        Container(
          width: double.infinity,
          height: 0.5,
          color: Colours.greyEE,
        )
      ]),
    );
  }

  headerData(String data, String title) {
    return SizedBox(
      width: 80,
      child: Column(
        children: [
          const SizedBox(height: 16),
          QkdText(data, fontSize: 16, fontWeight: FontWeight.w500),
          QkdText(title, color: Colours.grey99),
        ],
      ),
    );
  }

  body() {
    return Column(
      children: [
        Container(
          height: 40,
          color: Colours.white,
          width: double.infinity,
          child: Styles.tabbar(
              tabs: logic.tabs.map((e) => QkdText(e)).toList(),
              scrollable: true,
              controller: logic.tabC,
              labelPadding: const EdgeInsets.symmetric(horizontal: 12)),
        ),
        Expanded(
          child: Stack(
            children: [
              TabBarView(
                controller: logic.tabC,
                children: List.generate(logic.tabs.length, (index) {
                  if (logic.listType[index] == ListType.soccer) {
                    return UserViewPointList(1, logic.data!.expertId!);
                  } else if (logic.listType[index] == ListType.basket) {
                    return UserViewPointList(2, logic.data!.expertId!);
                  } else if (logic.listType[index] == ListType.planForm) {
                    return UserPlanFormList(logic.data?.expertId ?? "",
                        tag: '${Get.arguments}$random');
                  } else {
                    return UserPublishList(
                      logic.data?.userId,
                      logic.data?.expertId,
                      logic.listType[index],
                      tag: '${Get.arguments}$random',
                    );
                  }
                }),
              ),
              if (logic.listType[logic.tabIndex] != ListType.planForm)
                Positioned(
                    bottom: MediaQuery.of(context).padding.bottom + 32,
                    left: 8,
                    right: 8,
                    child: SubsBar(expertId: logic.data?.expertId ?? ""))
            ],
          ),
        )
      ],
    );
  }
}
